package com.blueocean_health.care.management.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.blueocean_health.care.management.common.LocalManager;
import com.blueocean_health.care.management.common.base.string.StringUtils;
import com.blueocean_health.care.management.domain.base.SysResult;
import com.blueocean_health.care.management.domain.base.UserAccount;
import com.blueocean_health.care.management.domain.base.UserTeam;
import com.blueocean_health.care.management.domain.dto.FlowListDto;
import com.blueocean_health.care.management.domain.dto.RoleFromUserManagerDto;
import com.blueocean_health.care.management.domain.dto.UserAccountDto;
import com.blueocean_health.care.management.domain.dto.UserAccountManagerDto;
import com.blueocean_health.care.management.domain.dto.UserListDto;
import com.blueocean_health.care.management.domain.dto.UserManagerListDto;
import com.blueocean_health.care.management.domain.vo.LoginDataVo;
import com.blueocean_health.care.management.domain.vo.UserAccountManagerDvo;
import com.blueocean_health.care.management.domain.vo.UserListDvo;
import com.blueocean_health.care.management.em.EnableStatusEnum;
import com.blueocean_health.care.management.em.LocalManagerType;
import com.blueocean_health.care.management.em.RoleTypeEnum;
import com.blueocean_health.care.management.em.UserSourceTypeEnum;
import com.blueocean_health.care.management.mapper.UserCompanyMapper;
import com.blueocean_health.care.management.mapper.UserTeamFromUserManagerMapper;
import com.blueocean_health.care.management.service.OrgAndProjectService;
import com.blueocean_health.care.management.service.UserCompanyService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

/**
 * 用户信息 2018年7月12日14:06:18
 * @author wuyanli
 *
 */
@Service
public class UserCompanyServiceImpl implements UserCompanyService{
	
	@Autowired
	private UserCompanyMapper userDao;
	
	@Autowired
	private UserTeamFromUserManagerMapper teamDao;
	
	@Autowired
	private OrgAndProjectService proService;

	@Override
	@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
	public SysResult addUser(UserAccountManagerDvo userDvo) {
		UserAccount user = userDvo.getUser();
		List<UserTeam> list = userDvo.getList();
		LoginDataVo courrentUser = LocalManager.getVal(LocalManagerType.LOGIN_DATA);
//		String teamId = "111";
//		String firstOrg = "1";
//		String teamId = courrentUser.getCurrentTeam().getTeamId()+"";
		String firstOrg = courrentUser.getUser().getFirstOrg()+"";
//		user.setTeamId(teamId);
		user.setFirstOrg(firstOrg);
		user.setOrgOrProject("1");
		if(StringUtils.isEmpty(user.getPassword()) || StringUtils.isEmpty(user.getUserName())){
			return SysResult.error("登录名称或密码不能为空");
		}
		user.setPassword(DigestUtils.md5Hex(user.getPassword()));
		UserAccountDto userByUserName = userDao.getUserByUserNameOrId(user.getUserName(),null);
		if(!StringUtils.isEmpty(userByUserName)){
			return SysResult.error("登录账号不允许重复，请重新输入");
		}
		
		userDao.addUser(user);
		UserAccountDto userByName = userDao.getUserByUserNameOrId(user.getUserName(),null);
		
		for (UserTeam userTeam : list) {
			userTeam.setUserId(userByName.getUserId());
			userTeam.setCreateTime(new Date());
			userTeam.setUpdateTime(new Date());
			userTeam.setCategory(null);
			//新增 为角色状态   1启用，2禁用 3已删除
			Integer roleStatus = teamDao.getRoleStatus(userTeam.getRoleId()+"");
			userTeam.setIsActive(roleStatus);
		}
//		teamDao.insertUserTeamBase(list);
		teamDao.insertList(list);
		
		return SysResult.ok();
	}

	@Override
	@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
	public SysResult updateUser(UserAccountManagerDvo userDvo) {
		UserAccount user = userDvo.getUser();
		List<UserTeam> list = userDvo.getList();
		int size = userDao.getUserSizeByUserName(user.getUserId()+"", user.getUserName());
		if(size > 0){
			return SysResult.error("登录账号不允许重复，请重新输入");
		}
//		user.setPassword(DigestUtils.md5Hex(user.getPassword()));
		userDao.updateUser(user);
		teamDao.deleteUserTeamByUserId(user.getUserId()+"");
		for (UserTeam userTeam : list) {
			userTeam.setUserId(user.getUserId());
			userTeam.setUpdateTime(new Date());
			userTeam.setCreateTime(new Date());
			if("0".equals(userTeam.getCategory())){
				userTeam.setCategory(null);
			}
			//新增   1启用，2禁用 3已删除
			if(StringUtils.isEmpty(userTeam.getIsActive())){
				//新增 为角色状态   1启用，2禁用 3已删除
				Integer roleStatus = teamDao.getRoleStatus(userTeam.getRoleId()+"");
				userTeam.setIsActive(roleStatus);
			}
		}
//		teamDao.insertUserTeamBase(list);
		teamDao.insertList(list);
		return SysResult.ok();
	}

	/**
	 * 负责人下拉列表 只有组织的用户
	 */
	@Override
	public List<UserManagerListDto> getUserList(Map<String,String> map) {
		LoginDataVo courrentUser = LocalManager.getVal(LocalManagerType.LOGIN_DATA);
		map.put("firstOrg", courrentUser.getUser().getFirstOrg()+"");
//		String firstOrg = "";
//		userDvo.setFirstOrg(courrentUser.getUser().getFirstOrg()+"");
		List<UserManagerListDto> userList = userDao.getUserList(map);
		return userList;
	}

	@Override
	public UserAccountManagerDto getUserInfo(String userId) {
		UserAccountManagerDto userDto = new UserAccountManagerDto();
		UserAccountDto user = userDao.getUserByUserNameOrId(null,userId);
		user.setUserSourceName(UserSourceTypeEnum.valueOf("_"+user.getUserSource()).getVal());
		userDto.setUser(user);
		List<RoleFromUserManagerDto> roleByUser = teamDao.getRoleByUser(userId);
		userDto.setList(roleByUser);
		return userDto;
	}
	
	@Override
	public PageInfo<UserListDto> getUserCompanyList(UserListDvo userDvo) {
		LoginDataVo courrentUser = LocalManager.getVal(LocalManagerType.LOGIN_DATA);
//		String firstOrg = "";
		userDvo.setFirstOrg(courrentUser.getUser().getFirstOrg()+"");
		String teamId = userDvo.getTeamId();
		if(StringUtils.isEmpty(teamId)){
			teamId = courrentUser.getCurrentTeam().getTeamId()+"";
		}
		List<String> allSubTeamId = proService.getAllSubTeamId(teamId);	
		userDvo.setTeamIdList(allSubTeamId);
		int pageSize = userDvo.getPageSize();
		int page = userDvo.getPage();
		PageHelper.startPage(page,pageSize);
		List<UserListDto> userManagerList = userDao.getUserCompanyList(userDvo);
		for (UserListDto userListDto : userManagerList) {
			String enableStatusName = StringUtils.isEmpty(userListDto.getEnableStatus())? "" : EnableStatusEnum.valueOf("_"+userListDto.getEnableStatus()).getVal();
			userListDto.setEnableStatusName(enableStatusName);
			String orgOrProName = StringUtils.isEmpty(userListDto.getOrgOrProject())?"":RoleTypeEnum.valueOf("_"+userListDto.getOrgOrProject()).getVal();
			userListDto.setOrgOrProjectName(orgOrProName);
			String userSourceName = StringUtils.isEmpty(userListDto.getUserSource())?"":UserSourceTypeEnum.valueOf("_"+userListDto.getUserSource()).getVal();
			userListDto.setUserSourceName(userSourceName);
		}
		PageInfo<UserListDto> pageInfo = new PageInfo<UserListDto>(userManagerList);
		return pageInfo	;
		
	}


	@Override
	public List<FlowListDto> getTeamRoleList() {
		Map<String,Object> map = new HashMap<>();
		LoginDataVo courrentUser = LocalManager.getVal(LocalManagerType.LOGIN_DATA);
		List<FlowListDto> flowList = new ArrayList<>();
		FlowListDto flowListDto = new FlowListDto();
		flowListDto.setName("组织");
		flowListDto.setValue("1");
		flowList.add(flowListDto);
		FlowListDto flowListDto2 = new FlowListDto();
		flowListDto2.setName("项目");
		flowListDto2.setValue("2");
		flowList.add(flowListDto2);
		
		String firstOrg = courrentUser.getUser().getFirstOrg()+"";
		String teamId = courrentUser.getCurrentTeam().getTeamId()+"";
//		String parentTeamId = courrentUser.getCurrentTeam().getParentTeamId()+"";
//		String parentTeamId = "";
//		String firstOrg = "50";
//		String teamId = "50";
		List<String> allSubTeamId = proService.getAllSubTeamId(teamId);		
//		String teamIds = allSubTeamId.toString();
		//一级组织Id和组织Id相同说明 没有父级
//		if(firstOrg.equals(teamId)){
//			parentTeamId = "";
//		}
		map.put("firstOrg", firstOrg);
		map.put("teamId", allSubTeamId);
//		map.put("parentTeamId", parentTeamId);
		
		for (FlowListDto flowDto : flowList) {
			map.put("type", flowDto.getValue());
//			List<TeamRoleListDto> teamRoleList = teamDao.getTeamRoleList(map);
			List<FlowListDto> typeList = teamDao.getTeamList(map);
			flowDto.setChildren(typeList);
		}
		
		return flowList;
	}

	@Override
	public List<UserListDto> getUserListExcel(UserListDvo userDvo) {
		LoginDataVo courrentUser = LocalManager.getVal(LocalManagerType.LOGIN_DATA);
		String firstOrg = courrentUser.getUser().getFirstOrg()+"";
//		String firstOrg = "";
		userDvo.setFirstOrg(firstOrg);
		userDvo.setFirstOrg(courrentUser.getUser().getFirstOrg()+"");
		String teamId = userDvo.getTeamId();
		if(StringUtils.isEmpty(teamId)){
			teamId = courrentUser.getCurrentTeam().getTeamId()+"";
		}
		List<String> allSubTeamId = proService.getAllSubTeamId(teamId);	
		userDvo.setTeamIdList(allSubTeamId);
		List<UserListDto> userManagerList = userDao.getUserCompanyList(userDvo);
		for (UserListDto userListDto : userManagerList) {
			String enableStatusName = StringUtils.isEmpty(userListDto.getEnableStatus())? "" : EnableStatusEnum.valueOf("_"+userListDto.getEnableStatus()).getVal();
			userListDto.setEnableStatusName(enableStatusName);
			String orgOrProName = StringUtils.isEmpty(userListDto.getOrgOrProject())?"":RoleTypeEnum.valueOf("_"+userListDto.getOrgOrProject()).getVal();
			userListDto.setOrgOrProjectName(orgOrProName);
			String userSourceName = StringUtils.isEmpty(userListDto.getUserSource())?"":UserSourceTypeEnum.valueOf("_"+userListDto.getUserSource()).getVal();
			userListDto.setUserSourceName(userSourceName);
		}
		return userManagerList;
	}

	@Override
	public int updateEnableStatus(String userId, String enableStatus) {
		int updateEnableStatus = userDao.updateEnableStatus(userId, enableStatus);
		return updateEnableStatus;
	}
	
}
